import { storeToRefs } from 'pinia'
import FirstToThirdCtgy from '@/piniaviews/ctgy/service'
import bookStore from '@/piniastore/book'
import ShopCart from './shopcart'
import { ref } from 'vue'
import { BookInfo } from '@/piniastore/book/state'

// 图书组件相关业务层
export default class Books {
  static store = bookStore()
  static storeRefs = storeToRefs(this.store)
  static isReadyAsc = ref(true) // 控制价格升序和价格降序的图标显示

  static sortField = ref('monthsalecount') // 排序的字段
  static ascOrDesc = ref('desc') // desc降序(大的在前，小的在后面) asc升序(小的在前面，大的在后面)


  // 根据图书3级分类id保存查询对应图书信息
  static async findBooksByThirdCtgyId(sortField: string = 'originalprice', ascOrDesc: string = 'asc') {
    const thirdCtgyId = FirstToThirdCtgy.store.getThirdCtgy.thirdctgyid // 获取跳转路由时3级分类id
    await Books.store.findBooksByThirdCtgyId(thirdCtgyId, sortField, ascOrDesc) // 根据图书3级分类id保存查询对应图书信息
    const shopCartList = ShopCart.store.shopCartList
    if (!shopCartList || shopCartList.length === 0) {
      await ShopCart.findCurUserShopCartLst() // 获取当前用户id对应的购物车信息
    }
    Books.uptBookNumWithSCLstNum()
  }

  // 更新图书购买数量
  static updateBookNum(bookNum: number, curbookisbn?: string) {
    const booklist = Books.store.getBookList // 获取图书列表
    let book: BookInfo
    for (let i = 0; i < booklist.length; i++) {
      book = booklist[i] // 获取当前书籍列表中的一本书信息
      if (curbookisbn && curbookisbn === book.ISBN) { // 更新书籍列表中指定的书籍购买数量
        book.purcharsenum = bookNum
        break
      }
      if (curbookisbn === undefined) { // 更新书籍列表中所有书籍购买数量
        book.purcharsenum = bookNum
      }
    }
    return booklist
  }

  // 动态给每本图书添加一个 purcharsenum 字段
  static uptBookNumWithSCLstNum() {
    ShopCart.uptBookNumWithSCLstNum(this.updateBookNum(0))
  }

  // 排序
  static sortBook = (_sortFiled: string) => {
    this.sortField.value = _sortFiled // 保存排序字段
    if (_sortFiled === 'originalprice') {
      this.isReadyAsc.value = !this.isReadyAsc.value
    }
    // 如果是降序就修改成升序，如果是升序就修改为降序
    this.ascOrDesc.value = this.ascOrDesc.value === 'desc' ? 'asc' : 'desc'

    this.findBooksByThirdCtgyId(_sortFiled, Books.ascOrDesc.value)
  }
}
